<!--
功能：数据列表解析页面
作者：李成
日期：2023年11月30
-->
<script setup lang="ts">
import { ref, onMounted, nextTick } from "vue";
import type { pageModel } from "./utils/types.ts";
import { getFormStructAndData, saveDataFormd } from "@/api/dataList";
import { message } from "@/utils/message";
import { useDataList } from "./utils/hooks";
const tableRef = ref();
const { treeList } = useDataList(tableRef);

const parentID = ref();
parentID.value = 0;

const generateForm = ref();
const editData = ref();
const jsonData = ref();
const isSuccess = ref(false);
const props = withDefaults(defineProps<pageModel>(), {
  modeID: 0,
  rsID: 1,
  isSearch: false,
  tableName: "",
  isSuccess: false,
  isSheng: false,
  editCode: 0
});

onMounted(async () => {
  //获取表单结构和表单数据
  const Result = await getFormStructAndData({
    modeID: props.modeID,
    rsID: props.rsID
  });
  isSuccess.value = props.isSuccess;
  jsonData.value = JSON.parse(Result.result.formStruct);
  editData.value = JSON.parse(Result.result.formData);
  console.log(props, "props");
  nextTick(() => {
    generateForm.value.refresh();
    if (Result.result.hideFields != null) {
      generateForm.value.hide(Result.result.hideFields);
    }
    if (Result.result.enabledFields != null) {
      generateForm.value.disabled(Result.result.enabledFields, true);
    }
    parentID.value = editData.value[0].PID;
    console.log(parentID.value, "pID");
    generateForm.value.setData(editData.value[0]);
  });
});

const saveJson = async () => {
  const myfalg = true;
  generateForm.value.validate().then(async () => {
    generateForm.value.getData().then(async data => {
      data.PID = parentID.value;
      console.log(parentID.value, data);

      const Result = await saveDataFormd({
        rsID: props.rsID,
        jsonStr: JSON.stringify(data),
        tableName: props.tableName,
        isSheng: props.isSheng,
        editCode: props.editCode
      });

      if (Result.isSuccess) {
        message("保存成功！", { type: "success" });
        //emit("delModel", true);
        isSuccess.value = true;
        //return false;
      } else {
        message(Result.msg, { type: "error" });
        isSuccess.value = false;
      }
    });
  });
  return myfalg;
};

defineExpose({ saveJson, isSuccess });
//const emit = defineEmits(["delModel"]);
</script>

<template>
  <el-form-item label="根类别" style="padding-left: 20px">
    <el-cascader
      class="w-full"
      v-model="parentID"
      :options="treeList"
      :props="{
        value: 'id',
        label: '指标名称',
        emitPath: false,
        checkStrictly: true
      }"
      clearable
      filterable
      placeholder="请选择根类别"
    >
      <template #default="{ node, data }">
        <span>{{ data.指标名称 }}</span>
        <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
      </template>
    </el-cascader>
  </el-form-item>
  <fm-generate-form
    :data="jsonData"
    ref="generateForm"
    :edit="!props.isSearch"
  />
</template>
